﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PdfForm
{
    public partial class PdfForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        /*
         * This function creates a pdf with the data that is given in the textbox
         */
        protected void Button1_Click(object sender, EventArgs e)
        {
            // Step 1: Creating a new pdf document.
            using (Document doc = new Document())
            {
                // Step 2: Create the pdf writer
                PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);

                // Step 3: Open the newly created document
                doc.Open();

                // step 4
                /*
                 * create document header; shows GMT time when PDF created.
                 * We instead write content to an **absolute** position 
                 * on the document
                 */
                Rectangle page = doc.PageSize;
                PdfPTable header = new PdfPTable(1);
                header.TotalWidth = page.Width;
                Phrase phrase = new Phrase(
                    DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT",
                    new Font(Font.FontFamily.TIMES_ROMAN, 12)
                );
                PdfPCell c = new PdfPCell(phrase);
                c.Border = Rectangle.NO_BORDER;
                c.VerticalAlignment = Element.ALIGN_TOP;
                c.HorizontalAlignment = Element.ALIGN_CENTER;
                header.AddCell(c);
                /*
                 * @param: (first row, last row (-1 writes all rows), left offset, **bottom** yPos of the table
                 */
                header.WriteSelectedRows(0, -1, 0,
                    page.Height - doc.TopMargin + header.TotalHeight + 20,
                    writer.DirectContent
                );

                /*
                 * add tabular data
                 */
                // table heading
                // Adds the data given in the text box here
                Paragraph userContent = new Paragraph(TextBox1.Text.ToString());
                Paragraph congrats = new Paragraph("congratulations, you wrote a pdf file!");
                userContent.Alignment = 1;
                congrats.Alignment = 1;
                doc.Add(userContent);
                doc.Add(congrats);
                // Step 5: Close the document which is done automagically
            }
        }
    }
}